package com.spdzen.controller.admin;

import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.spdzen.model.VideoCategory;
import com.spdzen.service.VideoCategoryService;
import com.spdzen.support.AdminLoginUtils;
import com.spdzen.support.LogUtils;
import com.spdzen.support.exception.ResultCodeException;
import com.spdzen.support.result.JsonResult;

@Controller
@RequestMapping("/admin/video/category")
public class VideoCategoryController {
	@Resource
	private VideoCategoryService videoCategoryService;
	
	@RequestMapping("/pageView.do")
	public String pageView(){
		return "/admin/video/videoCategoryPageView";
	}
	
	@RequestMapping(path = {"/add.do"}, method = {RequestMethod.POST})
	@ResponseBody
	public JsonResult addCategory(VideoCategory record, HttpServletRequest request) {
		try {
			record.setId(null);
			record.setOperateId(AdminLoginUtils.getUserId());
			record.setOperateTime(new Date());
			
			videoCategoryService.insertIfPermission(record);
			return JsonResult.success();
		} catch (ResultCodeException e) {
			return new JsonResult(e.getResultCode());
		} catch (Exception e) {
			LogUtils.logError(e, record);
			return JsonResult.error();
		}
	}
	
	@RequestMapping(path = {"/update.do"}, method = {RequestMethod.POST})
	@ResponseBody
	public JsonResult updateCategory(VideoCategory record, HttpServletRequest request) {
		try {
			record.setOperateId(AdminLoginUtils.getUserId());
			record.setOperateTime(new Date());
			
			videoCategoryService.updateIfPermission(record);
			return JsonResult.success();
		} catch (ResultCodeException e) {
			return new JsonResult(e.getResultCode());
		} catch (Exception e) {
			LogUtils.logError(e, record);
			return JsonResult.error();
		}
	}
	
	@RequestMapping(path = {"/delete.do"})
	@ResponseBody
	public JsonResult deleteCategory(Long id, HttpServletRequest request) {
		if(id == null || id.longValue() < 1){
			return JsonResult.errorParameter();
		}
		
		try {			
			return new JsonResult(videoCategoryService.deleteIfPermision(id));
		} catch (Exception e) {
			LogUtils.logError(e, id);
			return JsonResult.error();
		}
	}
	
	@RequestMapping("/queryAll.do")
	@ResponseBody
	public JsonResult queryAll(){
		try {
			return JsonResult.success(videoCategoryService.selectAll());
		} catch (Exception e) {
			LogUtils.logError(e);
			return JsonResult.error();
		}
	}
	
	@RequestMapping("/queryById.do")
	@ResponseBody
	public JsonResult queryById(Long id){
		if(id == null || id.longValue() < 1){
			return JsonResult.errorParameter();
		}
		
		try {
			return JsonResult.success(videoCategoryService.selectById(id));
		} catch (Exception e) {
			LogUtils.logError(e);
			return JsonResult.error();
		}
	}
}
